/*************************************************************************
	> File Name: builtin_cmd.c
	> Author: 
	> Mail: 
	> Created Time: Tue 22 Oct 2019 08:15:17 AM PDT
 ************************************************************************/

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <signal.h>
#include <stdlib.h>
#include <readline/history.h>
#include <readline/readline.h>

#include "env.h"

int is_builtin_cmd(char path[512])
{
    if (!strcmp(path, "cd"))
        return IS_MATCHING;
    if (!strcmp(path, "exit"))
        return IS_MATCHING;
    /*
    if (!strcmp(path, "echo"))
        return 1;*/
    if (!strcmp(path, "history"))
        return IS_MATCHING;

    return IS_NOT_MATCHING;
}

/**
 *@brief 实现cd命令， 改变路径
 */
int bulitin_cmd_cd(char path[512])
{
    int ret;
    
    printf("%s\n", path);
    ret = chdir(path);

    if (ret == -1) {
        perror("chdir error\n");
        return FAULT;
    }

    return TURE;
}

int bulitin_cmd_exit(void)
{
    int ret;
    pid_t pid;

    pid = getpid();

    ret = kill(pid, SIGHUP);
    if (ret == -1) {
        perror("kill error\n");
        exit(EXIT_FAILURE);
    }

    return TURE;
}

int builtin_cmd_history(void)
{
    int his_count = 0;
    HIST_ENTRY **his;

    his = history_list();
    if (!his) {
        perror("history_list error\n");
        return FAULT;
    }

    while (his[his_count]) {
        printf("%s\n", his[his_count]->line);
        his_count++;
    }

    return TURE;
}

int exec_builtin_cmd(char *argclist[512])
{
    if (!strcmp(argclist[0], "cd")) {
        if (argclist[1] == 0)
            return TURE;

        bulitin_cmd_cd(argclist[1]);
    }
    
    if (!strcmp(argclist[0], "exit")) {
        if (argclist[1] != 0)
            return TURE;

        bulitin_cmd_exit();
    }

    if (!strcmp(argclist[0], "history")) {
        if (argclist[1] != 0)
            return TURE;

        builtin_cmd_history();
    }
    /*
        if (!strcmp(argclist[0], "echo") {
            while (argclist[argc_num])
                printf("%s", argclist[argc_num]);
                printf("\n");
        }
    */
    return TURE;
}